<?php
/**
 * 题导入
 * User: cxm
 * Date: 2020/12/4
 * Time: 11:09
 */
namespace App\Jobs;

use App\Models\Question;
use App\Models\QuestionImportErrorLog;
use App\Models\QuestionImportRecord;
use App\Models\QuestionOptions;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Redis;
use Log;

class QuestionUpload implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * The number of times the job may be attempted.
     * 最大失次数
     * @var int
     */
    public $tries = 5;

    /**
     * The number of seconds the job can run before timing out.
     * 队列任务最大运行时长（秒）
     * @var int
     */
    public $timeout = 120;

    private $lot;

    /**
     * 插入数据数组
     */
    private $insertData = [];

    /**
     * @var array 选项数组
     */
    protected $excel_site;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($lot)
    {
        $this->lot = $lot;
        $this->excel_site = ["","","A","B","C","D",'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T'];
    }

    /**
     * Determine the time at which the job should timeout.
     *
     * @return \DateTime
     */
    public function retryUntil()
    {
        return now()->addSeconds(5);
    }

    /**
     * Execute the job.
     * \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['date'])
     * @return void
     */
    public function handle()
    {
        Log::info('导入名称--'.$this->lot);
        $item = DB::table('question_import_record')->where('lot', $this->lot)->first();
        Log::info('导入信息--'.json_encode($item));
        // 数据总数
        $count = Redis::llen($item->redis_title);
        Log::info("导入的数据量--".$count);
        // 导入的数据
        $excelData = Redis::LRANGE($item->redis_title,0,-1);
        //Log::info("导入的数据--".json_encode($excelData));
        $num = 0;
        if ($excelData) {
            foreach ($excelData as $key=>$item) {
                $num++;
                $data = json_decode($item,true);
                $res = $this->handleData($data);
                Log::info("处理的数据--{$key}---".json_encode($res));
            }
            QuestionImportRecord::where('lot',$this->lot)->update(['status'=>3,'finish_time'=>Carbon::now()]);
        }
        // 如果没有数据，删除此队列job
        if ($count == $num) {
            // 加入错误日志
            $this->addError();
            $this->job->delete();
        }
    }

    /**
     * 处理数据
     * @param $excelData
     * @return mixed
     */
    public function handleData($excelData){
        $title = trimall($excelData[0]);
        // 查看题是否存在
        if (!Question::where('title',$title)->first()) {
            // 题主表信息
            $data = [
                'title'                     => $title,
                'answer'                    => trimall($excelData[1]),
                'created_at'                => Carbon::now()
            ];

            // 加入题
            $question_id = Question::insertGetId($data);
            $excel_site = $this->excel_site;
            // 获取选项
            $newArr = [];
            for ($i=2;$i<12;$i++) {
                if (!empty($excelData[$i])) {
                    $newArr[] = [
                        'question_id'       => $question_id,
                        'option'            => $excel_site[$i],
                        'content'           => $excelData[$i],
                        'sort'              => $i - 1,
                        'created_at'        => Carbon::now()
                    ];
                }
            }
            QuestionOptions::insert($newArr);
        }
        return true;
    }

    /**
     * 插入题选项数据
     * @param $insertData
     * @return mixed
     */
    public function insertData($insertData){
        Log::info("添加的数据---".json_encode($insertData));
        QuestionOptions::insert($insertData);
        return true;
    }

    /**
     * 加入错误日志
     */
    public function addError(){
        $data = Redis::LRANGE($this->lot.'_err',0,-1);
        $insert = [];
        if (!empty($data)) {
            foreach ($data as $key=>$item) {
                $itemData = json_decode($item,true);
                $insert[] = [
                    'uuid'      => guid(),
                    'lot'       => $this->lot,
                    'excel_data'=> json_encode($itemData['excel_data']),
                    'msg'       => $itemData['msg'],
                    'created_at'=> Carbon::now()
                ];
            }
        }
        QuestionImportErrorLog::insert($insert);
        // 删除redis
        Redis::del($this->lot.'_err');
    }
}